package flickr.api.test;


import java.io.*;
import java.text.DateFormat;
import java.util.*;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.photos.Exif;
import com.aetrion.flickr.photos.GeoData;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.photos.SearchParameters;


/**
 * Demonstration of howto use the ActivityInterface.
 *
 * @author mago
 * @version $Id: ActivityExample.java,v 1.3 2008/07/05 22:19:48 x-mago Exp $
 */
public class GPSTrackExtractor_UTF_BB {
	static int picXpage = 100;
    static String apiKey = "4bae1b64fb25463bb3edd012d4f1ca46";
    static String sharedSecret = "11ae914f78506350";
    static String token = "72157622217282954-d14af7bc5fd7309e";
    
    
    Flickr f;
    REST rest;
    RequestContext requestContext;
    
  
   
    public GPSTrackExtractor_UTF_BB()
      throws ParserConfigurationException, IOException {
        f = new Flickr(apiKey,sharedSecret,new REST());
        requestContext = RequestContext.getRequestContext();
        Auth auth = new Auth();
        auth.setPermission(Permission.READ);
        auth.setToken(token);
        requestContext.setAuth(auth);
        Flickr.debugRequest = false;
        Flickr.debugStream = false;
    }

    public void showActivity(String latitude, String longitude, Calendar start, Calendar end, String output_file) throws IOException {
    	
    	PrintWriter out = new PrintWriter(new FileWriter(new File(output_file)));
    	
    	PhotosInterface pi = f.getPhotosInterface();
    	SearchParameters params = new SearchParameters();
    	params.setMinTakenDate(start.getTime());
    	params.setMaxTakenDate(end.getTime());
    	params.setLatitude(latitude);
    	params.setLongitude(longitude);
    	params.setRadius(4);
    	params.setRadiusUnits("km");
    	params.setHasGeo(true);
    	
    	int counter=0;
    	
    	PhotoList list = null;
		try {
			list = pi.search(params, picXpage, 1);
		} catch (FlickrException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	System.out.println("\nRetrievind data around ("+longitude+","+latitude+") from "+start.getTime()+" to "+end.getTime());
    	System.out.println(list.getTotal()+" pictures being retrieved...");
    	
    	for(int k=1; k<=list.getPages();k++) {
    		try {
				list = pi.search(params, picXpage, k);
			} catch (FlickrException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	for(int i=0; i<list.getPerPage();i++) {
	    		
	    			Photo x = (Photo)list.get(i);
	    			String description,title="";
	    			try {
						x = pi.getInfo(x.getId(), x.getSecret());
					} catch (SAXException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (FlickrException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
	    			//String description=x.getDescription().replace('\n', ' ');
	    			//String title=x.getTitle().replace('\n', ' ');
		    		String date = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.ITALY).format(x.getDateTaken());
		    		GeoData geo = x.getGeoData();
		    		String username = x.getOwner().getUsername();
		    		description=(x.getDescription());
		    		if (description!=null)
		    			description=description.replace('\n', ' ');
		    		title=(x.getTitle());
		    		if (title!=null)
		    			title=title.replace('\n', ' ');
		    		if(geo!=null){
		    			//out.println(username+"*"+geo.getLatitude()+"*"+geo.getLongitude()+"*"+geo.getAccuracy()+"*"+date);	
		    			if (description!=null)	
		    			try {
		    		        // Convert from Unicode to UTF-8
		    		        //String string = "abc\u5639\u563b";
		    		        byte[] utf8 = description.getBytes("UTF-8");
		    		    
		    		        // Convert from UTF-8 to Unicode
		    		        description = new String(utf8, "UTF-8");
		    		        System.out.println(description);
		    		    } catch (UnsupportedEncodingException e) {
		    		    	System.out.println(e);
		    		    }
		    		    
		    			out.println(username+"*"+title+"*"+description+"*"+geo.getLatitude()+"*"+geo.getLongitude()+"*"+geo.getAccuracy()+"*"+date);
		    			counter++;
		    		}
		    		/*else {
		    			Iterator <Exif>iter = pi.getExif(x.getId(), x.getSecret()).iterator();
		    			while(iter.hasNext()) {
		    				Exif exif = iter.next();
		    				String raw = exif.getLabel()+" "+exif.getRaw();
		    				if(raw.contains("atitude") || raw.contains("ongitude")) // avoid 1st letter for case sensitive
		    				System.out.println("!!! "+exif.getLabel()+" "+exif.getRaw());
		    			}
		    			System.out.println("broken picture @ page= "+k+" pic= "+i);
		    		}
		    		*/
	    		
	    	}
	    	
	    	System.out.println((100*k)/list.getPages()+"% Complete. Pictures "+counter+" on "+list.getTotal());
	    	
    	}
    	
    	out.close();
    }
    
public void showActivityBB(String city, double v1x, double v1y,double v3x, double v3y, Calendar start, Calendar end, String output_file) throws IOException {
    	
    	PrintWriter out = new PrintWriter(new FileWriter(new File(output_file)));
    	
    	PhotosInterface pi = f.getPhotosInterface();
    	SearchParameters params = new SearchParameters();
    	params.setMinTakenDate(start.getTime());
    	params.setMaxTakenDate(end.getTime());
    	System.out.println(String.valueOf(v1x));
    	params.setBBox(String.valueOf(v1x),String.valueOf (v1y),String.valueOf(v3x),String.valueOf (v3y));
    
    	params.setHasGeo(true);
    	
    	int counter=0;
    	
    	PhotoList list = null;
		try {
			list = pi.search(params, picXpage, 1);
		} catch (FlickrException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	System.out.println("\nRetrievind data around of "+city+"from "+start.getTime()+" to "+end.getTime());
    	System.out.println(list.getTotal()+" pictures being retrieved...");
    	
    	for(int k=1; k<=list.getPages();k++) {
    		try {
				list = pi.search(params, picXpage, k);
			} catch (FlickrException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	for(int i=0; i<list.getPerPage();i++) {
	    		
	    			Photo x = (Photo)list.get(i);
	    			String description,title="";
	    			try {
						x = pi.getInfo(x.getId(), x.getSecret());
					} catch (SAXException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (FlickrException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
	    			//String description=x.getDescription().replace('\n', ' ');
	    			//String title=x.getTitle().replace('\n', ' ');
		    		String date = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.ITALY).format(x.getDateTaken());
		    		GeoData geo = x.getGeoData();
		    		String username = x.getOwner().getUsername();
		    		description=(x.getDescription());
		    		if (description!=null)
		    			description=description.replace('\n', ' ');
		    		title=(x.getTitle());
		    		if (title!=null)
		    			title=title.replace('\n', ' ');
		    		if(geo!=null){
		    			//out.println(username+"*"+geo.getLatitude()+"*"+geo.getLongitude()+"*"+geo.getAccuracy()+"*"+date);	
		    			if (description!=null)	
		    			try {
		    		        // Convert from Unicode to UTF-8
		    		        //String string = "abc\u5639\u563b";
		    		        byte[] utf8 = description.getBytes("UTF-8");
		    		    
		    		        // Convert from UTF-8 to Unicode
		    		        description = new String(utf8, "UTF-8");
		    		        System.out.println(description);
		    		    } catch (UnsupportedEncodingException e) {
		    		    	System.out.println(e);
		    		    }
		    		    
		    			out.println(username+"*"+title+"*"+description+"*"+geo.getLatitude()+"*"+geo.getLongitude()+"*"+geo.getAccuracy()+"*"+date);
		    			counter++;
		    		}
		    		/*else {
		    			Iterator <Exif>iter = pi.getExif(x.getId(), x.getSecret()).iterator();
		    			while(iter.hasNext()) {
		    				Exif exif = iter.next();
		    				String raw = exif.getLabel()+" "+exif.getRaw();
		    				if(raw.contains("atitude") || raw.contains("ongitude")) // avoid 1st letter for case sensitive
		    				System.out.println("!!! "+exif.getLabel()+" "+exif.getRaw());
		    			}
		    			System.out.println("broken picture @ page= "+k+" pic= "+i);
		    		}
		    		*/
	    		
	    	}
	    	
	    	System.out.println((100*k)/list.getPages()+"% Complete. Pictures "+counter+" on "+list.getTotal());
	    	
    	}
    	
    	out.close();
    }
    
    public static void main(String[] args) {
        try {
            GPSTrackExtractor_UTF_BB t = new GPSTrackExtractor_UTF_BB();
        	//String city="PARISTEST";
            
    		
    		Locations city= Locations.TORINO;
    		String directoryName=city.getDescription()+"_BB";
    		File theDir = new File(directoryName);
    		
    		  // if the directory does not exist, create it
    		if (!theDir.exists()){
    		    System.out.println("Creo la directory: " + directoryName);
    		    theDir.mkdir();
    		}
            for(int month=0; month<13;month++)
            	
            	//PARIS
            	//t.showActivity("48.864310","2.323182",
            	//NY
            	//t.showActivity("40.761371","-73.981686",
            	//LONDON
                //t.showActivity("51.500183","-0.126214",
            	t.showActivityBB(city.getDescription(),city.getV1x(), city.getV1y(), city.getV3y(), city.getV3y(), 
                           new GregorianCalendar(2010,month,1,1,1,1),new GregorianCalendar(2013,month+1,1,1,1,1),
                           directoryName+"/output_"+month+".csv");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }

}
